package com.zwz.crawler.productdata;

import com.zwz.constant.Constant;
import com.zwz.parse.JsonParserUtil;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Slf4j
public class TungeeBrandList {
    public static void startTungeeBrandList( ) throws UnsupportedEncodingException {
        // 构建请求参数
        String enterpriseId = "577de19eadf21dc4";
        int start = 0;
        int end = 4;

        // URL编码处理（防止特殊字符）
        String encodedId = URLEncoder.encode(enterpriseId, "utf-8");

        // 构造完整URL
        String url = "https://sales.tungee.com/api/enterprise/brand/list"
                + "?enterprise_id=" + encodedId
                + "&start=" + start
                + "&end=" + end;

        try {
            Connection.Response response = Jsoup.connect(url)
                    .method(Connection.Method.GET)
                    // 设置完整请求头（严格匹配浏览器格式）
                    .header("authority", "sales.tungee.com")
                    .header("accept", "*/*")
                    .header("accept-encoding", "gzip, deflate, br, zstd")
                    .header("accept-language", "zh-CN,zh;q=0.9")
                    .header("cache-control", "no-cache")
                    .header("pragma", "no-cache")
                    .header("priority", "u=1, i")
                    .header("referer", "https://sales.tungee.com/enterprise-details/577de19eadf21dc4/enterprise-information/products")
                    .header("sec-ch-ua", "\"Not;A=Brand\";v=\"24\", \"Chromium\";v=\"128\"")
                    .header("sec-ch-ua-mobile", "?0")
                    .header("sec-ch-ua-platform", "\"Windows\"")
                    .header("sec-fetch-dest", "empty")
                    .header("sec-fetch-mode", "cors")
                    .header("sec-fetch-site", "same-origin")
                    .header("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36")
                    .header("x-tonxis-pid", "67864ea75f69e05d3b544ca7")
                    // 设置完整Cookie（需替换为浏览器最新值）
//                    .header("cookie", "_tx_pid=67864ea75f69e05d3b544ca7; __wpkreporterwid_=cc4a07fc-7bb9-40a4-96bc-2cbac34b658f; __last_enter_version=sales; _co_i=6805a5576eceb9637696f09d; _tx_uid=680701dddca941522b77e864; _tx_cid=6805a5576eceb9637696f09d; DISTINCT_ID=b84fe276-099f-4932-92b3-d54b92ae384b; _tx_sid=MTc0NTMwMTE0MzYyMjo4MmQ2OTQ5MTY0NjU2ODNmYjQ5MjlmMjc3NDg5ZDFlZg==; Hm_lvt_f2ee75449fc055cc4dbceb4fe403bea3=1745301094,1745302709; HMACCOUNT=B4E402DF057C895E; SecurityCenterDuId=ImFBSG15RzdPdVdPdCtsWnNGMFVuSXhVPSI.GujnjA.YBo4Zvc8vs4jgEmtioacknOQ9pE; tg_referrer_source=https%3A%2F%2Fuser.tungee.com%2F; Hm_lpvt_f2ee75449fc055cc4dbceb4fe403bea3=1745311256; acw_tc=1a0c399c17453135760595835e006b7083f6393f33c655626c1a0046fa440b; accountCenterSessionId=.eJwljLFOxDAQBf_F9RW73o3tuw7IiYZLmkNIaaK1vVaIoiAlOUAg_p0Iyvc0M9-mL4uugzlty00PZlbN_Srv2m9vfY7mVGRa9399zeZk2noYmq-EXf28tXU3dA8A7bUZn17On83jZWvGu-py7aamPlM33g_mYNIg86zTLn9o3Pdt1aX_i7kAvnKQnCaNR0dRGdFau0P_AAmFEhAjKGVHuWAJDhWzRo3Fo1eSkGzMwMLKnFLyXgjAgiQ4AoAvgXIILMJIPpIUqZJnmyogiZkryBgdcADrGDOrBVuU9nL2pObnF_SWVH8.Gujz5g.mabZACFOdMIQ51rQCEWcdKM4l10; doncusSessionId=eyJfZnJlc2giOmZhbHNlLCJ1c2VyX2lkIjoiNjgwNzAxZGRkY2E5NDE1MjJiNzdlODY0In0.Gujz9w.CcK7DDEO20T6xgpv_aKRIRfm7U8")
                    .header("cookie", Constant.cookies)
                    .ignoreContentType(true)
                    .ignoreHttpErrors(true)
                    .maxBodySize(0)  // 解除1MB响应限制
                    .timeout(30000)  // 设置30秒超时
                    .execute();

            // 输出结果
           log.info("HTTP状态码: " + response.statusCode());
           //log.info("响应内容:\n" + response.body());
            // 错误处理逻辑
            handleResponseErrors(response, enterpriseId);

            //解析
            JsonParserUtil.pasreProduct( response.body());

        } catch (IOException e) {
            System.err.println("网络请求异常: " + e.getMessage());
            e.printStackTrace();
        }
    }

    private static void handleResponseErrors(Connection.Response response, String enterpriseId) {
        switch (response.statusCode()) {
            case 401:
                System.err.println("认证失败可能原因：");
                System.err.println("1. Cookie已过期（需重新登录获取）");
                System.err.println("2. 缺少必要签名参数（检查是否需要以下头）");
                System.err.println("   - x-tonxis-signature");
                System.err.println("   - x-tonxis-sid");
                System.err.println("3. 企业ID无效: " + enterpriseId);
                break;
            case 403:
                System.err.println("权限不足：请确认企业ID归属");
                break;
            case 429:
                System.err.println("请求过于频繁：建议添加请求间隔（2-3秒）");
                break;
            default:
                if (response.statusCode() != 200) {
                    System.err.println("未知错误状态码: " + response.statusCode());
                }
        }
    }
}